package com.fenghongzhang.day016;

import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.BitmapFactory;
import android.media.MediaPlayer;
import android.os.Binder;
import android.os.Build;
import android.os.IBinder;
import android.util.Log;
import android.widget.RemoteViews;

import java.io.IOException;
import java.util.List;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;

/**
 * 不关闭的时候,不能停
 * startService
 *
 * 还调用服务中的方法.
 * bindService
 */
public class MusicService extends Service {

    private  Timer timer;
    private int index =0;
    private int playModel = 0;
    private MediaPlayer mediaPlayer;
    private List<Music> list;
    private static final String TAG = "MusicService";
    public MusicService() {
    }


    @Override
    public void onCreate() {
        Log.i(TAG, "onCreate: ");
        //初始化的工作
        super.onCreate();
        mediaPlayer = new MediaPlayer();
        list = MusicUtil.getData(this);

        //动态注册广播接收者
        MyBroadcast myBroadcast = new MyBroadcast();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("com.feng.pause");
        intentFilter.addAction("com.feng.restart");
        registerReceiver(myBroadcast,intentFilter);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.i(TAG, "onStartCommand: ");
        //开启一个定时器

        if(timer == null){
            timer  = new Timer();
            timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    sendNotify();
                }
            },0,1000);
        }

        return super.onStartCommand(intent, flags, startId);
    }

    private void sendNotify() {
        Notification.Builder builder = new Notification.Builder(this);
        builder.setSmallIcon(R.mipmap.ic_launcher);
//        builder.setContentTitle("标题");

        //自定义通知的布局
        RemoteViews remoteViews = new RemoteViews(getPackageName(), R.layout.notify_layout);
        //先找到要改的id
        remoteViews.setTextViewText(R.id.notify_title,list.get(index).getTitle());
        remoteViews.setImageViewBitmap(R.id.notify_img,
                BitmapFactory.decodeFile(MusicUtil.getPIc(this,list.get(index).getAlbumId())));


        //设置进度
        remoteViews.setProgressBar(R.id.pBar,
                Integer.parseInt(list.get(index).getDuration()),
                mediaPlayer.getCurrentPosition(),
                false);



        //点击暂停的时候,会发送一条频道为com.feng.pause的广播.
        //然后建立一个广播接收者,去接收这条广播,然后调用暂停的方法.
        Intent intent1 = new Intent();
        intent1.setAction("com.feng.pause");
        PendingIntent broadcast = PendingIntent.getBroadcast(this, 0, intent1, 0);
        //设点击事情,点击以后干啥
        remoteViews.setOnClickPendingIntent(R.id.notify_pause,broadcast);
        Intent intent2 = new Intent();
        intent2.setAction("com.feng.restart");
        PendingIntent broadcast2 = PendingIntent.getBroadcast(this, 0, intent2, 0);
        //设点击事情,点击以后干啥
        remoteViews.setOnClickPendingIntent(R.id.notify_restart,broadcast2);
        builder.setCustomContentView(remoteViews);
        startForeground(1,builder.build());
    }


    //建立广播接收者
    //广播接收的注册方式.1静态,2.动态.
    class MyBroadcast extends BroadcastReceiver{
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if(action.equals("com.feng.pause")){
                pause();
            }else if(action.equals("com.feng.restart")){
                restart();
            }
        }
    }


    @Override
    public void onDestroy() {
        Log.i(TAG, "onDestroy: ");
        super.onDestroy();
    }

    @Override
    public IBinder onBind(Intent intent) {
        Log.i(TAG, "onBind: ");
        return new MyBinder();
    }

    class MyBinder extends Binder{
//        public void callPlay(int i){
//            play(i);
//        }
//        public void callPause(){
//            pause();
//        }
//        public void callRestart(){
//            restart();
//        }
        //解决一下方法多的问题.
        //拿到当前service对象
        public MusicService getService(){
            return MusicService.this;
        }
    }

    @Override
    public boolean onUnbind(Intent intent) {
        Log.i(TAG, "onUnbind: ");
        return super.onUnbind(intent);
    }

    //播放
    public void play(int i){
        index = i;
        //重新发送一个相同id的通知.
        sendNotify();

        Log.i(TAG, "play: ");
        mediaPlayer.reset();
        try {
            mediaPlayer.setDataSource(list.get(i).getData());
            mediaPlayer.prepareAsync();
            mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                @Override
                public void onPrepared(MediaPlayer mp) {
                    Log.i(TAG, "onPrepared: ");
                    mediaPlayer.start();
                }
            });
        } catch (IOException e) {
            e.printStackTrace();
        }
        //播放完成监听器
        mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                switch (playModel){
                    case MusicUtil.PLAY_MODEL_ORDER:

                        break;
                    case MusicUtil.PLAY_MODEL_RANDOM:
                        int i1 = new Random().nextInt();
                        play(i1);
                        //随机
                        break;
                    case MusicUtil.PLAY_MODEL_SINGLE:
                        //单曲
                        play(index);
                        break;
                }
            }
        });

    }


    //反回当前的index
    public int getIndex() {
        return index;
    }

    //暂停
    public void pause(){
        mediaPlayer.pause();
    }

    //继续
    public void restart(){
        mediaPlayer.start();
    }
    //上一首
    public void pre(){
        if(--index <= 0){
            index = 0;
        }
        play(index);
    }
    //下一首


    //返回最大值
    public int getMax(){
       return mediaPlayer.getDuration();
    }
    //返回值当前播放的值
    public int getCorrectPosition(){
        return mediaPlayer.getCurrentPosition();
    }

    //接收页面的传值
    public void setProgress(int progress){
        mediaPlayer.seekTo(progress);
    }

    //播放模式
    public void setPlayModel(int playModel) {
        this.playModel = playModel;
    }
}
